import torch
import torch.nn as nn
from torch.nn import functional as F
from vit_model import VisionTransformer




# 定义残差块ResBlock
class ResidualBlock(nn.Module):
    def __init__(self, inchannel, outchannel, stride=1):
        super(ResidualBlock, self).__init__()
        # 这里定义了残差块内连续的2个卷积层
        self.left = nn.Sequential(
            nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(outchannel),
            nn.ReLU(inplace=True),
            nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(outchannel)
        )
        self.shortcut = nn.Sequential()
        if stride != 1 or inchannel != outchannel:
            # shortcut，这里为了跟2个卷积层的结果结构一致，要做处理
            self.shortcut = nn.Sequential(
                nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(outchannel)
            )

    def forward(self, x):
        out = self.left(x)
        # 将2个卷积层的输出跟处理过的x相加，实现ResNet的基本结构
        residual_out = out + self.shortcut(x)
        # vit = VisionTransformer(
        #     image_size=(224, 224),
        #     patch_size=(16, 16),
        #     emb_dim=residual_out.shape[1],
        #     mlp_dim=1024,
        #     num_heads=6,
        #     num_layers=2,
        #     num_classes=7,
        #     attn_dropout_rate=0.0,
        #     reapet_h=residual_out.shape[-1],
        #     first_cnn_channel = int(residual_out.shape[1]),
        #     dropout_rate=0.2)
        # vit.to('cuda:0')
        # # print("%%%%%%%%%%%% residual_out{} ".format(residual_out.shape))
        # vit_pred  = vit(out)
        # # print("%%%%%%%%%%%% vit_pred {} ".format(vit_pred.shape))
        # final_result = vit_pred*residual_out
        # print("%%%%%%%%%%%% residual_out{} ".format(residual_out.shape))
        out = F.relu(residual_out)
        # print("%%%%%%%%%%%% out{} ".format(out.shape))


        return out

class ResNet18(nn.Module):
    def __init__(self, num_classes=10):
        super(ResNet18, self).__init__()
        self.inchannel = 64
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU()
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(960, 512, kernel_size=3, stride=1, bias=False),
            nn.BatchNorm2d(512),
            nn.ReLU()
        )
        self.layer1 = self.make_layer(ResidualBlock, 64, 2, stride=1)
        self.layer2 = self.make_layer(ResidualBlock, 128, 2, stride=2)
        self.layer3 = self.make_layer(ResidualBlock, 256, 2, stride=2)
        self.layer4 = self.make_layer(ResidualBlock, 512, 2, stride=2)
        self.fc = nn.Linear(512, num_classes)

        self.encode1 = VisionTransformer(
            image_size=(224, 224),
            patch_size=(16, 16),
            emb_dim=64,
            mlp_dim=512,
            num_heads=3,
            num_layers=6,
            num_classes=7,
            attn_dropout_rate=0.0,
            reapet_h=224,
            first_cnn_channel = int(64),
            dropout_rate=0.2)

        self.encode2 = VisionTransformer(
            image_size=(112, 112),
            patch_size=(8, 8),
            emb_dim=128,
            mlp_dim=512,
            num_heads=3,
            num_layers=6,
            num_classes=7,
            attn_dropout_rate=0.0,
            reapet_h=224,
            first_cnn_channel=int(128),
            dropout_rate=0.2)

        self.encode3 = VisionTransformer(
            image_size=(56, 56),
            patch_size=(4, 4),
            emb_dim=256,
            mlp_dim=512,
            num_heads=3,
            num_layers=6,
            num_classes=7,
            attn_dropout_rate=0.0,
            reapet_h=224,
            first_cnn_channel=int(256),
            dropout_rate=0.2)

        self.encode4 = VisionTransformer(
            image_size=(28, 28),
            patch_size=(2, 2),
            emb_dim=512,
            mlp_dim=512,
            num_heads=3,
            num_layers=6,
            num_classes=7,
            attn_dropout_rate=0.0,
            reapet_h=224,
            first_cnn_channel=int(512),
            dropout_rate=0.2)



    # 这个函数主要是用来，重复同一个残差块
    def make_layer(self, block, channels, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)
        # print("%%%%%%%%%%%%% strides {} %%%%%%%%%%%".format(strides))
        layers = []
        for stride in strides:
            layers.append(block(self.inchannel, channels, stride))
            self.inchannel = channels
        return nn.Sequential(*layers)

    def forward(self, x):
        # 在这里，整个ResNet18的结构就很清晰了
        conv1_out = self.conv1(x)
        res_block1 = self.layer1(conv1_out)
        res_block2 = self.layer2(res_block1)
        res_block3 = self.layer3(res_block2)
        res_block4 = self.layer4(res_block3)
        # print("%%%%%%%%%%%%% conv1_out.shape{} %%%%%%%%%%%".format(conv1_out.shape))
        # print("%%%%%%%%%%%%% res_block1.shape {} %%%%%%%%%%%".format(res_block1.shape))
        # print("%%%%%%%%%%%%% res_block2.shape{} %%%%%%%%%%%".format(res_block2.shape))
        # print("%%%%%%%%%%%%% res_block3.shape{} %%%%%%%%%%%".format(res_block3.shape))
        # print("%%%%%%%%%%%%% res_block4.shape{} %%%%%%%%%%%".format(res_block4.shape))
        res_encoder1 = self.encode1(res_block1)
        # print("%%%%%%%%%%%%% res_encoder1.shape {} %%%%%%%%%%%".format(res_encoder1.shape))
        res_encoder2 = self.encode2(res_block2)
        # print("%%%%%%%%%%%%% res_encoder2.shape{} %%%%%%%%%%%".format(res_encoder2.shape))
        res_encoder3 = self.encode3(res_block3)
        # print("%%%%%%%%%%%%% res_encoder3.shape{} %%%%%%%%%%%".format(res_encoder3.shape))
        res_encoder4 = self.encode4(res_block4)

        res_en1 = res_encoder1 * res_block1
        res_en2 = res_encoder2 * res_block2
        res_en3 = res_encoder3 * res_block3
        res_en4 = res_encoder4 * res_block4

        # print("%%%%%%%%%%%%% res_en1.shape {} %%%%%%%%%%%".format(res_en1.shape))
        # res_en1_128 =self.conv2(res_en1)
        # print("%%%%%%%%%%%%% res_en1_128.shape{} %%%%%%%%%%%".format(res_en1_128.shape))
        res_en1_downsamp = F.interpolate(res_en1, size=(112, 112),mode='bilinear',align_corners=False)
        # print("%%%%%%%%%%%%% res_en1_downsamp.shape {} %%%%%%%%%%%".format(res_en1_downsamp.shape))
        res_en3_upsamp = F.interpolate(res_en3, size=(112, 112),mode='bilinear',align_corners=False)
        res_en4_upsamp = F.interpolate(res_en4, size=(112, 112), mode='bilinear', align_corners=False)
        concat_res = torch.cat((res_en1_downsamp,res_en2,res_en3_upsamp,res_en4_upsamp),dim=1)

        # print("%%%%%%%%%%%%% conda_res.shape {} %%%%%%%%%%%".format(concat_res.shape))
        out = self.conv2(concat_res)
        # print("%%%%%%%%%%%%% res_en2.shape {} %%%%%%%%%%%".format(res_en2.shape))
        # print("%%%%%%%%%%%%% res_en3.shape{} %%%%%%%%%%%".format(res_en3.shape))
        # print("%%%%%%%%%%%%% res_en4.shape{} %%%%%%%%%%%".format(res_en4.shape))
        # res_out1 = res_en1_downsamp + res_en2
        # print("%%%%%%%%%%%%% res_out1.shape {} %%%%%%%%%%%".format(res_out1.shape))
        # res_out2 = res_en3 + res_en4
        out = F.adaptive_avg_pool2d(out, (1,1))
        # print("%%%%%%%%%%%%% out.shape{} %%%%%%%%%%%".format(out.shape))
        out = out.view(out.size(0), -1)
        # print("%%%%%%%%%%%%% out.shape{} %%%%%%%%%%%".format(out.shape))
        out = self.fc(out)
        # print("%%%%%%%%%%%%% out.shape{} %%%%%%%%%%%".format(out.shape))
        return out


# net = ResNet18(num_classes=7)
# x = torch.randn((2, 3, 224, 224))
# net(x)
# # out = net(x)